import React, { useState, useEffect, ReactElement, isValidElement } from 'react';
import { message } from 'antd';
import { Redirect, connect, ConnectProps, Dispatch } from 'umi';
import { stringify } from 'querystring';
import { PageLoading } from '@ant-design/pro-layout';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/types/login';
import { getCurrentLoginUserId, getRoutes } from '@/utils/authority';


interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
  dispatch: Dispatch;
  queryMenuLoading: boolean;
}

// interface SecurityLayoutState {
//   isReady: boolean;
// }

const SecurityLayout: React.FC<SecurityLayoutProps> = (props) => {

  const [ready, setReady] = useState<boolean>(false);

  useEffect(() => {
    // 页面是否准备好
    setReady(true);
    const userId = getCurrentLoginUserId();
    // console.info('SecurityLayout.componentDidMount', userId);
    if (userId) {
      // 用户已存在，则查询菜单
      // 查询用户菜单信息，用户登录即查询
      const { dispatch } = props;
      dispatch({
        type: 'menu/getMenuData',
        payload: {
          userId
        }
      });
    }
  }, []);

  const { children, loading, queryMenuLoading } = props;
  // You can replace it to your authentication rule (such as check token exists)
  // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
  // console.info(currentUser);
  const userId = getCurrentLoginUserId();
  // 当前浏览器url
  const pathUrl = window.location.pathname;
  const protocol = window.location.protocol;
  const host = window.location.host;
  // http://localhost:8000/
  const urlStr = `${protocol}//${host}/`;
  let queryString;
  if (urlStr !== window.location.href) {
    queryString = stringify({
      redirect: window.location.href,
    });
  }
  // console.info(queryString);
  const routes = getRoutes();
  if(routes && pathUrl !== '/user/login' && routes.indexOf(pathUrl) < 0) {
    console.info('非法访问', pathUrl);
    message.warning('请勿访问未经授权的页面');
    return <Redirect to={`/user/login`} />;
  }
  // 没有登录，查询还没返回，显示正在加载
  // 菜单查询没有返回，也要显示正在加载
  // console.info('SecurityLayout--11', !userId, loading, !isReady, queryMenuLoading);
  if ((!userId && loading) || !ready || queryMenuLoading) {
    console.info('页面加载中');
    return <PageLoading />;
  }
  // 用户id为空，并且当前页面非登录页面，则跳转至登录页面
  if (!userId && pathUrl !== '/user/login') {
    // console.info('跳转至登录ing');
    if (queryString) {
      // console.info('跳转至登录ing2');
      return <Redirect to={`/user/login?${queryString}`} />;
    }
    // console.info('跳转至登录ing3');
    return <Redirect to={`/user/login`} />;
  }
  // console.info(typeof children);
  // console.info(children);
  if (isValidElement(children)) {
    return children as ReactElement<any, any>;
  }
  return null;
}

export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
  queryMenuLoading: loading.effects['menu/getMenuData'],
}))(SecurityLayout);
